var searchForm;
var drugName;
var drugStore;

function createSearchForm(i,title){
	
	searchForm = Ext.getCmp(title);
	
	if(searchForm != null)
		return searchForm;



var drug = Ext.data.Record.create( [ {
		name : 'drugId'
	}, {
		name : 'drugCode'
	} ,{name:'drugName'}
	  ,{name:'adrugName'}]);

	var proxy = new Ext.data.HttpProxy( {
		api : {
			read : 'getDrugs.html'
		}
	});

	var reader = new Ext.data.JsonReader( {
		totalProperty : 'total',
		successProperty : 'success',
		idProperty : 'drugId',
		root : 'drugModel',
		messageProperty : 'message' // <-- New "messageProperty" meta-data
	}, drug);
 drugStore = new Ext.data.Store( {
		id : 'drugStore',
		proxy : proxy,
		reader : reader
	});


/*----- EMIRATES CODE START HERE---*/
	var store =  new Ext.data.Store({
	proxy : new Ext.data.HttpProxy( {
			url : 'city.html'
		}),

		reader : new Ext.data.JsonReader( {
			root : 'cityModel'
			
		}, [ {
			name : 'gid',
			mapping : 'gid'
		}, {
			name : 'eName',
			mapping : 'eName'
		} , {
			name : 'aName',
			mapping : 'aName'
		}])
	});
	if(languageName=='arabic'){
		store.sort('aName','ASC');
	}else{
		store.sort('eName','ASC');
	}
	var cityCombo = {

		fieldLabel : cityLabel,
		xtype : 'combo',
		id : 'city'+i,
		store : store,
		selectOnFocus : true,
		triggerAction : 'all',
		listWidth : 110,
		typeAhead : true,
		mode : 'local',
		displayField : comboDisplayField,
		allowBlank : true,
		editable: true,
		valueField : 'gid',		
     		triggerAction : 'all',
		emptyText : allValue,
		onKeyUp : function(){

			//if(this.getEl().dom.value.length > 1){
			//	this.store.baseParams = {reg:this.getEl().dom.value.toLowerCase()};
				//this.store.reload();
				if(languageName=='arabic')
						this.store.filter("aName",this.getEl().dom.value,true,false);
					else
					this.store.filter("eName",this.getEl().dom.value,true,false);

this.onTriggerClick();

			

			//}

				}
	};

	var regstore =  new Ext.data.Store({
		proxy : new Ext.data.HttpProxy( {
				url : 'region.html'
			}),

			reader : new Ext.data.JsonReader( {
				root : 'regionModelMap',
				autoLoad : true
			}, [ {
				name : 'gid',
				mapping : 'gid'
			}, {
				name : 'eName',
				mapping : 'eName'
			}, {
				name : 'aName',
				mapping : 'aName'
			} ])
		});


			if(languageName=='arabic'){
		regstore.sort('aName','ASC');
	}else{
		regstore.sort('eName','ASC');
	}

		var regionCombo = {

			fieldLabel : regionLabel,	
			//style: 'padding-right:15px',
			cls:'regComboCls',
			xtype : 'combo',
			id : 'region'+i,
			store : regstore,
			selectOnFocus : true,
			triggerAction : 'all',
			listWidth : 150,
			typeAhead : true,
			mode : 'remote',
			displayField : comboDisplayField,
			allowBlank : true,
				autoSelect:true,
			editable: true,
			valueField : 'gid',		
			
			triggerAction : 'all',
				
				onKeyUp : function(){

			//if(this.getEl().dom.value.length > 1){
			//	this.store.baseParams = {reg:this.getEl().dom.value.toLowerCase()};
				//this.store.reload();

					if(languageName=='arabic')
						this.store.filter("aName",this.getEl().dom.value,true,false);
					else
					this.store.filter("eName",this.getEl().dom.value,true,false);
this.onTriggerClick();



			//}

				},
		
			listeners : {
			
				'select' : function(cmb, rec, idx) {
		
				
									var combo1 = Ext.getCmp('city'+i);
									combo1.clearValue();
									combo1.store.load( {
									params : {
										
										'id' : ''+rec.data.eName+''
									}

								});
						
				}
			}
		};

		if(languageName=='arabic'){
			fisrtItem=cityCombo;
			secondItem=regionCombo;			
		}else{
			fisrtItem=regionCombo;
			secondItem=cityCombo;			
		}
	var nationalityStore = new Ext.data.Store( {
		proxy : new Ext.data.HttpProxy( {
			url : 'nationality.html'
		}),

		reader : new Ext.data.JsonReader( {
			root : 'nationalityListMap',
			autoLoad : true
		}, [ {
			name : 'nationalityId',
			mapping : 'nationalityId'
		}, {
			name : 'nationalityName',
			mapping : 'nationalityName'
		}, {
			name : 'nationalityaName',
			mapping : 'nationalityaName'
		} ])
	});

	var nationalityCombo = {
		fieldLabel : nationalityLabel,
		xtype : 'combo',
		id : 'nationality'+i,
		store : nationalityStore,
		selectOnFocus : true,
		triggerAction : 'all',
		listWidth : 110,
		typeAhead : true,
		mode : 'remote',
		displayField : natioanalityDisplayField,
		allowBlank : true,
		editable: true,
		valueField : 'nationalityId',
		anchor : '55%',
		triggerAction : 'all',
			emptyText: allValue,
		autoSelect : true
		
	};



	var activityStore = new Ext.data.Store( {
		proxy : new Ext.data.HttpProxy( {
			url : 'activity.html'
		}),
		
		reader : new Ext.data.JsonReader( {
			root : 'activityListMap',
			autoLoad : true
		}, [ {
			name : 'activityId',
			mapping : 'activityId'
		}, {
			name : 'activityName',
			mapping : 'activityName'
		}, {
			name : 'activityaName',
			mapping : 'activityaName'
		} ])
	});

	var activityCombo = {
		fieldLabel : activityLabel,
		xtype : 'combo',
		id : 'activity'+i,
		store : activityStore,
		selectOnFocus : true,
		triggerAction : 'all',
		listWidth : 110,
		typeAhead : true,
		mode : 'remote',
		displayField : activityDisplayField,
		allowBlank : true,
		editable: true,
			autoSelect : true,
		valueField : 'activityId',
		anchor : '55%',
		triggerAction : 'all',
		emptyText: allValue
		/*listeners : {
			'select' : function(cmb, rec, idx) {
				Ext.Ajax.request( {
							url : 'bbox.htm?id=' + rec.data.roadId + '&name=' + 'street',
							success : function(response, options) {
								var wkt = response.responseText;
								highlightPolygon(wkt, 'street');
							},
							failure : function(response, options) {
							}
						});
			}
		}*/
	};
	
	
	var officialsStore = new Ext.data.Store( {
		proxy : new Ext.data.HttpProxy( {
			url : 'officials.html'
		}),
		
		reader : new Ext.data.JsonReader( {
			root : 'officialListMap',
			autoLoad : true
		}, [ {
			name : 'id',
			mapping : 'id'
		}, {
			name : 'type',
			mapping : 'type'
		}, {
			name : 'atype',
			mapping : 'atype'
		} ])
	});

	var officialCombo = {
		fieldLabel : caughtByLabel,
		xtype : 'combo',
		id : 'official'+i,
		store : officialsStore,
		selectOnFocus : true,
		triggerAction : 'all',
		listWidth : 150,
		typeAhead : true,
			autoSelect : true,
		mode : 'remote',
		displayField : officialDisplayField,
		allowBlank : true,
		editable: true,
		valueField : 'id',
		anchor : '55%',
			emptyText: allValue,
		triggerAction : 'all'
		
	};
	
	
	drugStore.load({start:1});

	drugStore.on('load', function(drugStore) {
  for(var i = 0; i <drugStore.data.items.length; i++){
	 

if(drugStore.data.items[i].data.drugName== title.trim()){

drugStore.data.items[i].checked = true;
}

if(drugStore.data.items[i].data.adrugName== title.trim()){

drugStore.data.items[i].checked = true;
}
   }
//	drugStore.getAt(rec.id).checked = true;
    
});
	var CheckboxCombo = new Ext.ux.form.CheckboxCombo( {
		
	
		id:'drug' + i,
	hiddenName: 'drugId',
	fieldLabel : drugTitle,	
		triggerAction : 'all',
	store: drugStore,
			valueField: 'drugCode',
			allowBlank : false,
	displayField: drugComboDisplayField

	});

	
	

	unitCombo = [ [ 1, 'KG' ], [ 2, 'Gm' ],
		                         			[ 3, 'lb' ], [ 4, 'ton' ] ];


	var unitTypeStore = new Ext.data.SimpleStore( {
		fields : [ 'unitid', 'unitValue' ],
		data : unitCombo
	});

	var unitTypeCombo = {
		fieldLabel : '',
		xtype : 'combo',
		id  : 'unit'+i,
		store : unitTypeStore,
		selectOnFocus : true,
		triggerAction : 'all',
		listWidth : 210,
		typeAhead : true,
		mode : 'local',
		displayField : 'unitValue',
		allowBlank : true,
		editable: false,
		valueField : 'unitid',
			hiddenName : 'unitValue',
		anchor : '95%',
		triggerAction : 'all',
		emptyText : ""
	};





			var inputquantity={
			 xtype:'textfield',
				
				 	 width  : 175,
		      fieldLabel:'Quantity',
		       name:'quantity',
		      id:'quantity'+i
		};
		
	
		
			
			searchForm =		new Ext.FormPanel({
				labelWidth:  80,				
				bodyStyle: 'padding:5px',				
				frame:false,
					id:title,
			
				width:340,
					height:540,
				border:false,
				//autoScroll: true,
					
				items: [CheckboxCombo,{
	id:'searchby'+i,
xtype:'combo',
	width:80
,fieldLabel:searchbyTitle,
	allowBlank : false
,store:[byArrestValue,byQuantityValue],
	autoSelect : true,
		emptyText:'',
		 triggerAction: 'all',
		anchor : '55%',
		 editable: true
},
		
	
	{
	id:'type'+i,
xtype:'combo',
	width:80
,fieldLabel:searchLocationLabel,
		store:[departmentValue,regionLabel],
		autoSelect : true,
		emptyText:'',
			allowBlank : false,
		anchor : '55%',
		 triggerAction: 'all'
	},
	
	
	
	{
		 

id:"year"+i,		
	xtype: 'checkboxcombo',
	
		mode : 'local',
		fieldLabel : yearsLabel,
		style : 'font-size:11px;',
		emptyText : '',
				allowBlank : false,
		store : new Ext.data.ArrayStore( {
			style : 'font-size:11px;',
			fields : [ 'value', 'label' ],
			data : [ [ '1', '1421' ], [ '2', '1422' ],
					[ '3', '1423' ], [ '4', '1424' ],
					[ '5', '1425' ], [ '6', '1426' ],
					[ '7', '1427' ], [ '8', '1428' ]]
		}),
		valueField : 'value',
				displayField : 'label'



	},
		 				  {
														 // column layout with 2 columns
														 layout:'column'
														 // defaults for columns
														 ,defaults:{
														 columnWidth:0.5
														 ,border:false
														 ,xtype:'panel'
														 ,layout:'form'
														 ,bodyStyle:'padding:0 0px 0 0'
														 }
														 ,items:[{
															
														 // left column
														 // defaults for fields
														 defaults:{anchor:'100%'}
														 ,items:[
fisrtItem
]},{
	 // right column
	 // defaults for fields
	 defaults:{anchor:'100%'}
	 ,items:[secondItem]
}]
							 }
							
							
							
							,activityCombo,officialCombo,nationalityCombo
				],
		 
				 buttons:[{
	         			
							iconCls:'searchbtnbg',
						id:"search"+i,	
							
	         			formBind: true,
	         			// Function that fires when user clicks the button
	         			handler:function(){
							searchForm=Ext.getCmp(title);
							
							searchForm.el.mask(pleaseWaitMessage, 'x-mask-loading');
							
	                	 searchForm.getForm().submit({
	                		 url : 'getArrest.html',
	             			params:{drugName:title,id:i},
	         				method:'POST', 

	         				success:function(form, action){
	             				searchForm.el.unmask(3000);
	         					searchResults = Ext.getCmp('searchResults_id');
								
	         				    arrestGrid = Ext.getCmp('arrestGridPan');
							if(!arrestGrid){
								addSearchResultGrid();
								searchResults.add(arrestGrid);
								
							}
	         				if(!searchResults.items)
								searchResults.add(arrestGrid);
							arrestGrid = Ext.getCmp('arrestGridPan');
							arrestGrid.getColumnModel().setHidden(5, true);
							if(byArrestValue==((Ext.get('searchby'+i).dom.value))){
								arrestGrid.getColumnModel().setHidden(4, false);
						arrestGrid.getColumnModel().setHidden(6, true);
							}else{
								arrestGrid.getColumnModel().setHidden(6, false);
								arrestGrid.getColumnModel().setHidden(4, true);
								
							}
						
	         				arrestGrid.store.loadData(action.result);
							arrestGrid.doLayout();
							Searchinfo.setActiveTab(1);
	         				Searchinfo.doLayout();
							

						if ((kmlLayer != '')&&(kmlLayer != null)){
               mapObj.removeLayer(kmlLayer);
               kmlLayer = "";
       } 
          clearAll();
     /*    kmlLayer = new OpenLayers.Layer.Vector("KML", {
         projection: mapObj.displayProjection,
         strategies: [new OpenLayers.Strategy.Fixed()],
         protocol: new OpenLayers.Protocol.HTTP({
         	 url: "../nis/kml/drug/" + action.result.kml + ".kml",
             format: new OpenLayers.Format.KML({
                 extractStyles: true,
                 extractAttributes: true
             })
         })
     });
           kmlLayer.setVisibility(true);
           kmlLayer.refresh({force: true});
           mapObj.addLayer(kmlLayer);
           selectControl = new OpenLayers.Control.SelectFeature(kmlLayer);
    
          kmlLayer.events.on({
         "featureselected": onFeatureSelect,
         "featureunselected": onFeatureUnselect
     });*/
          
      //  mapObj.addControl(selectControl);
       // selectControl.activate();  
       mapObj.zoomToMaxExtent();
     
       	if ((searchvectors != '')&&(searchvectors != null)){
               mapObj.removeLayer(searchvectors);
               searchvectors = "";
       } 
	    

	   if(action.result.kml != null){
		  
        function Geometry(symbol, maxSize, maxValue){
     		    this.symbol = symbol;
     		    this.maxSize = maxSize;
     		    this.maxValue = maxValue;
     		
     		    this.getSize = function(value){
     		        switch(this.symbol) {
     		            case 'circle': // Returns radius of the circle
     		            case 'square': // Returns length of a side
     		                return Math.sqrt(value/this.maxValue)*this.maxSize;
     		            case 'bar': // Returns height of the bar
     		                return (value/this.maxValue)*this.maxSize;
     		            case 'sphere': // Returns radius of the sphere
     		            case 'cube': // Returns length of a side
     		                return Math.pow(value/this.maxValue, 1/3)*this.maxSize;
     		        }
     		    };
     			
     		
        
}
var winha = null;
        var symbol = new Geometry('circle', 5,100000);
		  var context = {
            getSize: function(feature) {
                return 40 + Math.round(symbol.getSize(feature.attributes["quantity"]) * Math.pow(2,mapObj.getZoom()-1));
            },
            getChartURL: function(feature) {
			


		
                var values = feature.attributes["SECONL"] + ',' + feature.attributes["COCAN"]+ ',' + feature.attributes["CRAK"]+ ',' + feature.attributes["AFION"]+ ',' + feature.attributes["CHERONG"]+ ',' + feature.attributes["CGAATKG"]+','+feature.attributes["CHABOCNT"]+ ',' + feature.attributes["CHASG"]+ ',' + feature.attributes["AMPTMN"] +',' + feature.attributes["CPTG"] +',' + feature.attributes["OTHERS"] ;
              
				var size = 40+ Math.round(symbol.getSize(feature.attributes["quantity"]) * Math.pow(2,mapObj.getZoom()-1));
					
                var charturl = 'http://chart.apis.google.com/chart?cht=p&chd=t:' + values + '&chs=' + 60 + 'x' + 80 + '&chf=bg,s,ffffff00'+'&chco=023ddb|44a33d|88857f|ff5af9|f58121|be79ff|da2400|ffc400|00b2f1|800000|7ac943';
        
				return charturl;

            }
        };
     
      /*  var context = {


            getSize: function(feature) {
                return 20 + Math.round(symbol.getSize(feature.attributes["quantity"]) * Math.pow(2,mapObj.getZoom()-1));
            },
            getChartURL: function(feature) {
				var values =feature.attribute["CRAK"]+','+feature.attribute["COCAN"];
			
                var size = 20 + Math.round(symbol.getSize(feature.attributes["quantity"]) * Math.pow(2,mapObj.getZoom()-1));
                var charturl = 'http://chart.apis.google.com/chart?cht=p&chd=t:' + values + '&chs=' + size + 'x' + size + '&chf=bg,s,ffffff00';
                return charturl;
            }
        };*/


        var template = {
            fillOpacity: 1.0,
            externalGraphic: "${getChartURL}",
            graphicWidth: "${getSize}",
            graphicHeight: "${getSize}",
            strokeWidth: 0
        };

        var style = new OpenLayers.Style(template, {context: context});
	    var styleMap = new OpenLayers.StyleMap({'default': style, 'select': {fillOpacity: 0.7}});

	

         searchvectors = new OpenLayers.Layer.GML( internetUsers, ""+ action.result.kml + ".txt",
                { format: OpenLayers.Format.GeoJSON,
                  styleMap: styleMap,
                  isBaseLayer: false,
                  projection: new OpenLayers.Projection("EPSG:4326")} );
			
        	mapObj.addLayer(searchvectors);
			var ele = document.getElementById("legendpan");
	
	
    		ele.style.display = "block";
document.getElementById("legendpan").innerHTML = action.result.aml;


		
		
				searchForm.getForm().reset();
        	searchvectors.events.on({
                 "featureselected": onFeatureSelectSearch
                
             });
        	 var options = {
                     hover: true
                  };

                  var select = new OpenLayers.Control.SelectFeature(searchvectors, options);
                  mapObj.addControl(select);
                  select.activate();
           
        	
        	 function serialize() {
                 var Msg = "<strong>" + searchvectors.selectedFeatures[0].attributes["name"] + "</strong><br/>";
                 Msg    += "Population: " + searchvectors.selectedFeatures[0].attributes["quantity"] + "<br/>";
                 Msg    += "0-14 years: " + searchvectors.selectedFeatures[0].attributes["CRAK"] + "%<br/>";
                Msg    += "0-14 years: " + searchvectors.selectedFeatures[0].attributes["COCAN"] + "%<br/>";
                 
               //  document.getElementById("info").innerHTML = Msg;
             }
        	 
        	 
	   }
	  
	         			},

	         			// Failure function, see comment above re: success and failure.
	         			// You can see here, if login fails, it throws a messagebox
	         			// at the user telling him / her as much.  


	         			failure:function(form, action){
	         				if(action.failureType == 'server'){
	         					

	         					Ext.Msg.alert(noDataLabel, obj.errors.reason);
	         				}else{
								var value =	Ext.get('drug' + i).dom.value;
								if(value==""){
								//Ext.Msg.alert(drugsMandatory);
									Ext.Msg.show({
									      title:'',
									      msg: drugsMandatory,
									      icon : Ext.MessageBox.ERROR,
									      bodyStyle:'font-color:#ffffff',
									      buttons: Ext.MessageBox.OK
									    });
								searchForm.el.unmask();
	         				
							return;
								}
								 value =	Ext.get('searchby'+i).dom.value;
								
								if(value==""){
								//Ext.Msg.alert(searchbyMandatory);
									Ext.Msg.show({
									      title:'',
									      msg: searchbyMandatory,
									      icon : Ext.MessageBox.ERROR,
									      bodyStyle:'font-color:#ffffff',
									      buttons: Ext.MessageBox.OK
									    });
								searchForm.el.unmask();
	         				
							return;
								}
								
									 value =	Ext.get('type'+i).dom.value;
									  
								if(value==""){
								//Ext.Msg.alert(searchwiseMandatory);
									Ext.Msg.show({
									      title:'',
									      msg: searchwiseMandatory,
									      icon : Ext.MessageBox.ERROR,
									      bodyStyle:'font-color:#ffffff',
									      buttons: Ext.MessageBox.OK
									    });
								searchForm.el.unmask();
	         				
								return;
									
								}
								
								 value =	Ext.get('year'+i).dom.value;
								
								if(value==""){
								//Ext.Msg.alert(yearMandatory);
									Ext.Msg.show({
									      title:'',
									      msg: yearMandatory,
									      icon : Ext.MessageBox.ERROR,
									      bodyStyle:'font-color:#ffffff',
									      buttons: Ext.MessageBox.OK
									    });
								searchForm.el.unmask();
	         				
								return;
								}
								 
								
								else
	         					Ext.Msg.alert(warningLabel, authenticationUnreachable+': '+action.failureType);
							
	         				}
							searchForm.el.unmask();
	         				searchForm.getForm().reset();
	         			} 

	         			});
	         		}
	         		}]
			});
			
			
			
			
			
			
			
   
     	return searchForm;
	}; 
